package com.wubo.sec.core;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.wubo.common.util.ObjectUtils;

@SuppressWarnings("deprecation")
public class JdbcUserDetailsService implements UserDetailsService, MessageSourceAware {
	protected Log log = LogFactory.getLog(this.getClass());
	
	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
	
	public void setMessageSource(MessageSource messageSource) {
		if(messageSource != null){
			messages = new MessageSourceAccessor(messageSource);
		}
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		UserDetails user = UserLoginPageHelper.getLoginProcessor().login(username);
		
		if(user == null){
			log.warn("User"+username+" has not found .");
			throw new UsernameNotFoundException(
                    messages.getMessage("JdbcDaoImpl.notFound", new Object[]{username}, "Username {0} not found"), username);
		}
		 
		Collection<? extends GrantedAuthority> roles = user.getAuthorities();
		/* 新版：当没有为用户分配任何权限时，不再拒绝登录，而是给予一个每个通过认证用户都有的默认权限
		if( roles == null || roles.size() < 1){
			log.warn("User "+user.getUsername()+" has no Authority .");
			throw new UsernameNotFoundException(
                    messages.getMessage("JdbcDaoImpl.noAuthority",
                            new Object[] {username}, "User {0} has no GrantedAuthority"), username);
		}*/
		if(log.isDebugEnabled()){
			log.debug(ObjectUtils.objToString(roles, 2));
		}
		return user;
	}
	
}
